/**
 * Company : SIANGKLOM.
 * Created By : Chatree Siangklom
 * Created On : Oct 9, 2013  6:36:46 PM 
 * e-Mail : dr_chatree@hotmail.com
 * Mobile Phone : (+66) 087-921-5115
 * Package Name : sap.business.fi.outbound
 * File Name : InvoiceInterServices.java
 * TODO
 */
package sap.business.fi.outbound;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import promis.utility.CommonService;
import sap.business.commons.AbstractInter;
import sap.business.commons.IInterServices;
import sap.business.commons.JCOReturn;
import sap.business.commons.SapMessageReturn;
import sap.business.commons.SapTable;
import sap.business.enumeration.BAPI_STATUS;
import sap.business.enumeration.JCO_TABLE_STATUS;
import sap.business.enumeration.ResultStatus;
import sap.business.enumeration.STAGING_STATUS;
import sap.business.inter.exception.DataException;
import sap.business.inter.exception.JCOException;
import sap.business.inter.results.ResultBacked;
import sap.jco.client.Connection;
import sap.jco.client.SAPClientInfo;
import com.sap.conn.jco.AbapException;
import com.sap.conn.jco.JCoException;
import com.sap.conn.jco.JCoFunction;
import com.sap.conn.jco.JCoStructure;
import com.sap.conn.jco.JCoTable;
import com.tis.database.entitys.SapMessage;
import com.tis.database.entitys.staging.FiInvoiceOutb;
import com.tis.sap.mapping.sd.SAPField;

/**
 * @author Chatree Siangklom of Administrator
 * Date =Oct 9, 2013 : 6:36:46 PM 
 * CreateBy=Chatree Siangklom
 * 
 * InvoiceInterServices
 * TODO
 */
public class InvoiceInterServices extends AbstractInter<FiInvoiceOutb> implements IInterServices<FiInvoiceOutb, String> {
	
	private static final Logger logging = LoggerFactory.getLogger(InvoiceInterServices.class);
	
	/**
	 * Date =Oct 9, 2013 : 6:37:19 PM 
	 * CreateBy=Chatree Siangklom
	 * InvoiceInterServices
	 * TODO
	 * @param jcoConnection
	 * @param sapBapi
	 * @param sapTable0
	 * @param sapStructure0
	 * @param sapTableReturn0
	 */
	public InvoiceInterServices() {
		setBapiName("ZSAAR0003");
		setTableName("IT_RECEIPT_INV");
		setTableReturnName("RETURN");
		setTableOutputName("IT_OUTPUT");
	}

	/** (Javadoc)
	 * @see sap.business.commons.IInterServices#SynchroToSap(java.util.List)
	 * Date =Oct 11, 2013 : 11:13:25 AM 
	 * CreateBy=Chatree Siangklom
	 * TODO
	 */
	Connection conn = null;
	public SapMessageReturn<FiInvoiceOutb> SynchroToSap(List<FiInvoiceOutb> valueList) throws AbapException, Exception {
		System.out.println("SynchroToSap -----> Size =" + CommonService.getSize(valueList));
		
		setResultBacked(new ResultBacked());
		setSapMessageReturn(new SapMessageReturn<FiInvoiceOutb>());
		JCoFunction jCoFunction = null;
		JCoTable sapTable = null;
		JCoTable sapTableOutput = null;
		JCoTable sapTableReturn = null;
		
		try {
			conn = new Connection();
			jCoFunction = conn.getJCoFunction(getBapiName()); 
			logging.info((jCoFunction == null)?"JCOFunction is null":"JCOFunction is not null");
			
			sapTable = jCoFunction.getTableParameterList().getTable(getTableName());
			logging.info((sapTable == null)? getTableName() + " is null": getTableName() + " is not null");
			
			sapTableOutput = jCoFunction.getTableParameterList().getTable(getTableOutputName());
			logging.info((sapTableOutput == null)?getTableOutputName() + " is null": getTableOutputName() + " is not null");
			
			sapTableReturn = jCoFunction.getTableParameterList().getTable(getTableReturnName());
			logging.info((sapTableReturn == null)?getTableReturnName() + " is null": getTableReturnName() + " is not null");
			
		} catch (JCoException e) {
			e.printStackTrace();
			getResultBacked().setJcoException(new JCOException(e.getMessage()));
		} catch (Exception e) {
			e.printStackTrace();
			getResultBacked().setJcoException(new JCOException(e.getMessage()));
		}

		//Setp 1 : Sending Data to AP		
		SynchroToSap(jCoFunction, sapTable, valueList);
	
		//Setp 2 : Get Return Data form SAP 		
		CallbackMessageFromSap(sapTableOutput, sapTableReturn);		
		
		//Step 3 : set to Container resultBacked
		sapMessageReturn.setResultBacked(getResultBacked());
		sapMessageReturn.setOriginalval(valueList);
		
		//Setp 4 : return to go.
		System.out.println("Output size=" + CommonService.getSize(sapMessageReturn.getOutput()));
		System.out.println("Originalval size=" + CommonService.getSize(sapMessageReturn.getOriginalval()));
		return sapMessageReturn;
	}

	/** (Javadoc)
	 * @see sap.business.commons.IInterServices#SynchroToSap(com.sap.conn.jco.JCoFunction, com.sap.conn.jco.JCoTable, java.util.List)
	 * Date =Oct 11, 2013 : 11:13:25 AM 
	 * CreateBy=Chatree Siangklom
	 * TODO
	 */
	public ResultBacked SynchroToSap(JCoFunction jcoFunction,JCoTable jcoTable, List<FiInvoiceOutb> valueList) throws AbapException, Exception {
		logging.info("SynchroToSap Starting ...........>");
		try{
			
			if(!jcoTable.isEmpty())
			{
				logging.info("Bapi = "+ getBapiName() +", table "+ getTableName() +" is not Empty ");				
				getResultBacked().setResultStatus(new ResultStatus(BAPI_STATUS.Success.toString(), JCO_TABLE_STATUS.NotEmpty.toString()
						, STAGING_STATUS.WA.toString()));
				return getResultBacked();
			}
			
			logging.info("valueList size : " + valueList.size() + " //Table.getNumRows : " + jcoTable.getNumRows());	
			if(CommonService.getSize(valueList) > 0){				
				for (FiInvoiceOutb objval : valueList) 
		        {
					logging.info("InstanceNo =" + objval.getInstanceNo() + " -- PMS_STAGING_ID =" +  objval.getId() + " -- Sending value =" + objval.toString());
					jcoTable.appendRow();
					
					jcoTable.setValue(SAPField.Invoice.getBuzei(), objval.getGlPostingSeqNumber());
					jcoTable.setValue(SAPField.Invoice.getBukrs(), objval.getOrgCode());
					jcoTable.setValue(SAPField.Invoice.getBlart(), objval.getDocType());
					jcoTable.setValue(SAPField.Invoice.getBldat(), objval.getVoucherDate());
					jcoTable.setValue(SAPField.Invoice.getBudat(), objval.getPostingDate());
					jcoTable.setValue(SAPField.Invoice.getWaers(), objval.getCurrency());
					jcoTable.setValue(SAPField.Invoice.getBrnch(), objval.getBranchCode());
					jcoTable.setValue(SAPField.Invoice.getXblnr(), objval.getDocumentNo());
					jcoTable.setValue(SAPField.Invoice.getButxt(), objval.getNarration());
					jcoTable.setValue(SAPField.Invoice.getBschl(), objval.getPostingKey());
					jcoTable.setValue(SAPField.Invoice.getHkont(), objval.getAccountCode());
					jcoTable.setValue(SAPField.Invoice.getUmskz(), objval.getSpecialGl());
					jcoTable.setValue(SAPField.Invoice.getGsber(), objval.getBa());
					jcoTable.setValue(SAPField.Invoice.getPrctr(), objval.getCostCenter());
					jcoTable.setValue(SAPField.Invoice.getBvtyp(), objval.getBankType());
					jcoTable.setValue(SAPField.Invoice.getMwskz(), objval.getVatCode());
					jcoTable.setValue(SAPField.Invoice.getWrbtr(), objval.getAmount());
					jcoTable.setValue(SAPField.Invoice.getFwbas(), objval.getBaseAmount());
					jcoTable.setValue(SAPField.Invoice.getZfbdt(), objval.getBaseLineDate());
					jcoTable.setValue(SAPField.Invoice.getZounr(), objval.getDocumentNo());
					jcoTable.setValue(SAPField.Invoice.getXref1(), objval.getUnitNo());
					jcoTable.setValue(SAPField.Invoice.getXref2(), objval.getAccountCode2());
					jcoTable.setValue(SAPField.Invoice.getXref3(), objval.getRefDocNo());
					jcoTable.setValue(SAPField.Invoice.getSgtxt(), objval.getDescription1());
					jcoTable.setValue(SAPField.Invoice.getKindo(), objval.getDescription2());
					jcoTable.setValue(SAPField.Invoice.getKostl(), objval.getCostCtr());
					jcoTable.setValue(SAPField.Invoice.getAufnr(), objval.getInternalOrder());
					jcoTable.setValue(SAPField.Invoice.getProjk(), objval.getWbs());
					jcoTable.setValue(SAPField.Invoice.getZlsch(), objval.getDummy1());
		        }
				
				//Sending To SAP Processing
				if(jcoFunction != null)
					jcoFunction.execute(conn.getJCoConnection());
				else 
					throw new Exception("Can not execute jcoFunction is null.");
				
				ResultBacked rsb = getResultBacked();
				logging.info((rsb == null) ? "getResultBacked() is null." : "getResultBacked() is not null");
				
				JCoTable it_output = jcoFunction.getTableParameterList().getTable("IT_OUTPUT");		        
		        logging.info("SAP_STAGING_ID: " + it_output.getString("SAP_STAGING_ID") + " //EXT_REF_NO: " + it_output.getString("EXT_REF_NO") + " //MSG_CODE: " + it_output.getString("MSG_CODE") + " //MSG_DESC: " + it_output.getString("MSG_DESC"));
				
		        String msgCode = CommonService.IsNullRString(it_output.getString("MSG_CODE"));
				ResultStatus rs = new ResultStatus(BAPI_STATUS.Success.toString(), JCO_TABLE_STATUS.Success.toString(), msgCode);
				getResultBacked().setResultStatus(rs);
				
			}else
				getResultBacked().setDataException(new DataException("Find not found data row [" + this.toString() + "]"));
			
		}catch(Exception e){
			e.printStackTrace();
			getResultBacked().setJcoException(new JCOException(e.getMessage()));
			return getResultBacked();
		}		
		return getResultBacked();
	}

	/** (Javadoc)
	 * @see sap.business.commons.IInterServices#SynchroToSap(com.sap.conn.jco.JCoFunction, com.sap.conn.jco.JCoStructure, java.util.List)
	 * Date =Oct 11, 2013 : 11:13:25 AM 
	 * CreateBy=Chatree Siangklom
	 * TODO
	 */
	@Deprecated
	public void SynchroToSap(JCoFunction jcoFunction,
			JCoStructure jCoStructure, List<FiInvoiceOutb> valueList)
			throws AbapException, Exception {
		// TODO Auto-generated method stub
		
	}

	/** (Javadoc)
	 * @see sap.business.commons.IInterServices#SynchroToSap(com.sap.conn.jco.JCoFunction, com.sap.conn.jco.JCoTable, com.sap.conn.jco.JCoStructure, java.util.List)
	 * Date =Oct 11, 2013 : 11:13:25 AM 
	 * CreateBy=Chatree Siangklom
	 * TODO
	 */
	@Deprecated
	public void SynchroToSap(JCoFunction jcoFunction, JCoTable jcoTable,
			JCoStructure jCoStructure, List<FiInvoiceOutb> valueList)
			throws AbapException, Exception {
		// TODO Auto-generated method stub
		
	}

	/** (Javadoc)
	 * @see sap.business.commons.IInterServices#CallbackMessageFromSap(com.sap.conn.jco.JCoTable)
	 * Date =Oct 11, 2013 : 11:13:25 AM 
	 * CreateBy=Chatree Siangklom
	 * TODO
	 */
	@Deprecated
	public SapMessageReturn<FiInvoiceOutb> CallbackMessageFromSap(
			JCoTable jcoTable_return) throws AbapException, Exception {
		// TODO Auto-generated method stub
		return null;
	}

	/** (Javadoc)
	 * @see sap.business.commons.IInterServices#CallbackMessageFromSap(com.sap.conn.jco.JCoTable, com.sap.conn.jco.JCoStructure)
	 * Date =Oct 11, 2013 : 11:13:25 AM 
	 * CreateBy=Chatree Siangklom
	 * TODO
	 */
	public SapMessageReturn<FiInvoiceOutb> CallbackMessageFromSap( JCoTable jcoTable_return, JCoTable jCoReturn) throws AbapException, Exception {
		logging.info("Welcome SapMessageReturn --------------------->");
		try{
			logging.info((jcoTable_return == null)?"jcoTable_return is null":"jcoTable_return is not null size=" + jcoTable_return.getNumRows());
			logging.info((jCoReturn == null)?"jCoReturn is null":"jCoReturn is not null size=" + jCoReturn.getNumRows());

			new SapTable(null).JcoTableToString(jCoReturn);
			//Step 1 Get Message 
			if(jCoReturn != null && jCoReturn.getNumRows() > 0){
				System.out.println("Return.getNumRows =" + jCoReturn.getNumRows());
				for(int i = 0; i < jCoReturn.getNumRows(); i++)
				{
					jCoReturn.setRow(i);
					sapMessageReturn.setId(CommonService.IsNullRNull(jCoReturn.getString(SAPField.ReturnField.getId())));
					sapMessageReturn.setLogMsgNo(CommonService.IsNullRNull(jCoReturn.getString(SAPField.ReturnField.getLogMsgNo())));
					sapMessageReturn.setLogno(CommonService.IsNullRNull(jCoReturn.getString(SAPField.ReturnField.getLogNo())));				
					sapMessageReturn.setType(CommonService.IsNullRNull(jCoReturn.getString(SAPField.ReturnField.getType())));
					sapMessageReturn.setMessage(CommonService.IsNullRNull(jCoReturn.getString(SAPField.ReturnField.getMessage())));
				}
			}
			
			//Step 2 Get Outout table
			if(jcoTable_return != null && jcoTable_return.getNumRows() > 0)
			{
				new SapTable(null).JcoTableToString(jcoTable_return);
				
				List<SapMessage> outputlst = new ArrayList<SapMessage>();
				System.out.println("Update Message table Retrun getNumRows = " + jcoTable_return.getNumRows());
				for(int i = 0; i < jcoTable_return.getNumRows(); i++)
				{
					jcoTable_return.setRow(i);
					if(!CommonService.IsNull(jcoTable_return.getString("PMS_STAGING_ID"))){
						System.out.println(JCOReturn.toString(jcoTable_return));
						
						SapMessage output = new SapMessage();
						output.setId(CommonService.IsNullRNull(jcoTable_return.getString("PMS_STAGING_ID")));
						output.setSapStagingId(CommonService.IsNullRNull(jcoTable_return.getString("SAP_STAGING_ID")));
						output.setExtRefKey(CommonService.IsNullRNull(jcoTable_return.getString("SAP_STAGING_ID")));
						output.setExtRefNo(CommonService.IsNullRNull(jcoTable_return.getString(SAPField.Customer.getKunnr())));
						output.setMsgCode(CommonService.IsNullRNull(jcoTable_return.getString("MSG_CODE")));
						output.setMsgDesc(CommonService.IsNullRNull(jcoTable_return.getString("MSG_DESC")));
						output.setMsgAltDesc(CommonService.IsNullRNull(jcoTable_return.getString("MSG_ALT_DESC")));
						output.setSyncUpdatedby(SAPClientInfo.JCO_USER);
						output.setSyncUpdatedon(new Date());
						
						outputlst.add(output);
					}
				}
				
				sapMessageReturn.setOutput(outputlst);
			}
		}catch(Exception ee){
			logging.equals(ee.getMessage());
			ee.printStackTrace();
			throw ee;
		}
		
		return null;
	}

	/** (Javadoc)
	 * @see sap.business.commons.IInterServices#CallbackMessageFromSap(com.sap.conn.jco.JCoStructure)
	 * Date =Oct 11, 2013 : 11:13:25 AM 
	 * CreateBy=Chatree Siangklom
	 * TODO
	 */
	@Deprecated
	public SapMessageReturn<FiInvoiceOutb> CallbackMessageFromSap(
			JCoStructure jCoStructureReturn) throws AbapException, Exception {
		// TODO Auto-generated method stub
		return null;
	}

	/** (Javadoc)
	 * @see sap.business.commons.IInterServices#CallbackMessageFromSap(com.sap.conn.jco.JCoTable, java.util.List)
	 * Date =Oct 11, 2013 : 11:13:25 AM 
	 * CreateBy=Chatree Siangklom
	 * TODO
	 */
	@Deprecated
	public SapMessageReturn<FiInvoiceOutb> CallbackMessageFromSap(
			JCoTable jcoTable_return, List<FiInvoiceOutb> valueList)
			throws AbapException, Exception {
		// TODO Auto-generated method stub
		return null;
	}
}
